package com.xv.yan.filter;
import com.xv.yan.beans.entity.AdminDo;
import com.xv.yan.util.ExcludeResourceUtil;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//他新建了两个过滤器，解决一个是乱码问题，就是新建学生的时候输入非字母会乱码，第二个是登陆进去的路径在其他浏览器上不登陆也可以访问，他就是为了解决这两个问题的，然后我比着做完，登陆不上去了
//
@WebFilter(filterName = "AuthorizationFilter"
        ,urlPatterns = {"/*"}
)
//只有授权管理
public class AuthorizationFilter implements Filter{
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest=(HttpServletRequest) request;
        HttpServletResponse httpServletResponse=(HttpServletResponse) response;

        //过滤器排除静态资源
        String requestURI = httpServletRequest.getRequestURI();
        if (ExcludeResourceUtil.shouldExclude(requestURI)){
            //设置字符编码
            chain.doFilter(request,response);
        }else{
            HttpSession session = httpServletRequest.getSession();
            AdminDo admin = (AdminDo) session.getAttribute("adminDo");//这个在哪存的
            String contextPath = httpServletRequest.getContextPath();
            String path = requestURI.substring(contextPath.length());
            /**
             *这几个权限我不太懂啊
             */
            if (admin==null){
                if ("/loginServlet".equals(path)){
                    chain.doFilter(request,response);
                }else {//未登录且访问的路径不是公共路径
                    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request,response);
                }
            }else {
                chain.doFilter(request,response);
            }
        }
    }
}
